import { createRouter, createWebHashHistory } from 'vue-router';
import { closeNProgress, startNProgress } from '../utils/nprogress';
import routes from './router';
import { useRouteCacheStore } from '../store';

const router = createRouter({
  // history: createWebHistory(process.env.BASE_URL), // 使用History模式
  history: createWebHashHistory(), // 或者使用Hash模式
  routes,
});

router.beforeEach((to, from, next) => {
  startNProgress();
  const routeCacheStore = useRouteCacheStore();
  // 保存离开页面的滚动位置
  if (from.name) {
    const scrollY = window.scrollY;
    routeCacheStore.saveScrollPosition(from.name as string, scrollY);
  }
  // 保存路由的缓存
  routeCacheStore.addRouteCache(to);

  next();
});

router.afterEach(to => {
  // 恢复离开页面的滚动位置
  if (to.name) {
    const routeCacheStore = useRouteCacheStore();
    const savedPosition = routeCacheStore.getScrollPosition(to.name as string);

    // 使用setTimeout确保DOM已更新
    setTimeout(() => {
      window.scrollTo(0, savedPosition);
    }, 100);
  }
  closeNProgress();
});

export default router;
